<?php


namespace app\common\model;


use think\facade\Cache;
use think\Model;

class Article extends Model
{
    protected $autoWriteTimestamp = 'datetime';


    public function setPublishTimeAttr($value, $data)
    {
        $value = empty($value) ? null : $value;
        return $value;
    }

    public function columnInfo()
    {
        return $this->belongsTo(Column::class, 'column_id', 'id');
    }

    public static function getArticleList(
        $page = 1,
        $limit = 10,
        $where = [],
        $with = [],
        $field = '*',
        $order = 'id desc'
    )
    {
        return self::where($where)
            ->with($with)
            ->field($field)
            ->withCount(['comments'])
            ->page($page, $limit)
            ->order($order)
            ->select();
    }

    public static function getTagList()
    {
        $tagList = Cache::get('tag_list');
        if (empty($tagList)) {
            $tag = self::cache('tag_sql_cache')
                ->column('tag');
            $tagList = array_unique(explode(',', implode(',', $tag)));
            Cache::set('tag_list', $tagList, 360);
        }
        return $tagList;
    }

    /**
     * 返回字段中必须包含total字段
     * @param $title
     * @param $link
     * @param $order
     * @param string $field
     * @param int $limit
     */
    public static function getArticleRankingList($title, $link, $order, $cache, $field = '*', $limit = 10)
    {
        $rankingList = Cache::get($cache);
        if (empty($rankingList)) {
            $rankingList = Article::order($order)
                ->limit($limit)
                ->field($field)
                ->select();
            $ranking['title'] = $title;
            $ranking['link'] = $link;
            $ranking['url'] = 'article_read';
            $ranking['list'] = $rankingList;
            Cache::set($cache, $rankingList, 360);
        }

        return $ranking;
    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'goal_id', 'id')->where(['goal_type' => 'article', 'status' => 1]);
    }
}
